#!/bin/sh 
#usages:  ./create_kvm_image.sh [rootfs_dir] [image_name] [disk_size(GB)] [ostype] [uuid]

if [ $# < 4 ]
then 
   exit 
fi 
  
TARGET_DIR=$1
TARGET_IMAGE=$2
TARGET_SIZE=$3
#add by jch
TARGET_OS=$4
if [ $# == 4 ]
then
   VM_UUID=""
else
   VM_UUID=$5
fi

echo $TARGET_OS

echo $TARGET_SIZE


CHS_H=16 
CHS_S=63 
CHS_C=`expr $TARGET_SIZE \* 1024 \* 2048 / $CHS_H / $CHS_S`
echo $CHS_C

SEEK_OFFSET=`expr $CHS_C \* $CHS_H \* $CHS_S - 1` 

rm $TARGET_IMAGE.img 
dd if=/dev/zero of=$TARGET_IMAGE.img seek=$SEEK_OFFSET bs=512 count=1 

LOOP_DEV=`losetup -f` 
losetup $LOOP_DEV $TARGET_IMAGE.img 

fdisk $LOOP_DEV -C $CHS_C -H $CHS_H -S $CHS_S <<EOF 
n
p
1


w
EOF

MAPPER=`echo $LOOP_DEV | sed 's/dev\//&mapper\//'`"p1"

kpartx -a $LOOP_DEV
mkfs.ext3 $MAPPER

DISK_UUID=`vol_id --uuid $MAPPER` 

TMP_DIR=`mktemp -d` 
mount $MAPPER $TMP_DIR 
cp -a $TARGET_DIR/* $TMP_DIR

#add by jch
# designate default install dir of grub 
GRUB_INSTALL_DIR=""
if [ "$TARGET_OS" == "fedora" ]
then
	GRUB_INSTALL_DIR="/usr/share/grub/i386-redhat/*"
else
	GRUB_INSTALL_DIR=" /usr/lib/grub/i386-pc/*"
fi

chroot $TMP_DIR <<EOF
mkdir -p /etc/ivic
touch /etc/ivic/vm.yaml
echo uuid:$VM_UUID > /etc/ivic/vm.yaml

mkdir -p /boot/grub
cp $GRUB_INSTALL_DIR /boot/grub

exit
EOF


mount --bind /dev $TMP_DIR"/dev"
echo "(hd0) "$TARGET_IMAGE".img" >> device.map

grub --device-map=device.map <<EOF
root (hd0,0)
setup (hd0)
quit
EOF

DEVICE_MAP=$TMP_DIR"/boot/grub/device.map"
MENU_LST=$TMP_DIR"/boot/grub/menu.lst"

echo "(hd0) UUID="$DISK_UUID >> $DEVICE_MAP

if [ "$TARGET_OS" == "debian" ]
then
   chroot $TMP_DIR <<EOF
update-grub
exit
EOF

   sed -i "s/kopt=.*/kopt=root=UUID=${DISK_UUID} ro/" $MENU_LST
   sed -i "s/groot=.*/groot=(hd0,0)/" $MENU_LST

   chroot $TMP_DIR <<EOF
update-grub
exit
EOF
else
   SEARCH_PATH=$TMP_DIR"/boot/"
   scriptPath=`dirname $0`
   ""$scriptPath"/"make_menu_list.sh linux $DISK_UUID $SEARCH_PATH $MENU_LST
fi
#sed -i "s/root=\/dev\/mapper.*/root=UUID=${DISK_UUID}/" $MENU_LST
#sed -i "s/root=UUID=.*/root=UUID=${DISK_UUID}/" $MENU_LST

umount $TMP_DIR"/dev"
umount $TMP_DIR 
rmdir $TMP_DIR
kpartx -d $LOOP_DEV
losetup -d $LOOP_DEV
rm device.map 


#grub --no-floppy --batch <<EOF 
#device (hd0) $TARGET_IMAGE.img 
#geometry (hd0) $CHS_C $CHS_H $CHS_S 
#root (hd0,0) 
#setup (hd0) 
#quit
#EOF 

